<script setup lang="ts">
//行为
import { ElMessage, type FormRules } from 'element-plus'
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { loginAPI } from '@/apis/login'
import { setLocalToken } from '@/utils/auth'
import type { LoginParams } from '@/types/login'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'


// 1.表单数据
const formData = ref<LoginParams>({
  mobile: '15036048879',
  code: '246810',
})

//导入路由对象，
const router = useRouter()

const store = useUserStore()

// 2.校验规则
const rules = ref<FormRules<LoginParams>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: 'blur' },
  ],
})

// 3.登录
const formRef = ref<FormInstance>()
const onSubmit = () => {
  formRef.value?.validate(async(valid) => {
    if (valid) {
      const res= await loginAPI(formData.value)
      setLocalToken(res.data.token)
      store.setToken(res.data.token)
      //登录成功后跳转首页
      router.push('/home')
      ElMessage.success('登录成功')
    }
  })
}
</script>

<template>
  <!--结构 -->
  <div class="container">
    <el-card>
      <img class="logo" src="@/assets/images/logo.png" alt="" />
      <el-form :model="formData" :rules="rules" ref="formRef">
        <el-form-item label="手机号：" prop="mobile">
          <el-input placeholder="请输入手机号" v-model="formData.mobile"></el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item label="验证码：" prop="code">
          <el-input v-model="formData.code" placeholder="请输入验证码"></el-input>
        </el-form-item>

        <!-- 用户协议 -->
        <el-form-item prop="">
          <el-checkbox>我已阅读并同意</el-checkbox>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item label="" prop="">
          <el-button type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
        {{ formData }}
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url('@/assets/images/login.png');

  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
    .el-form {
      padding: 0 20px;
      .el-button {
        width: 100%;
      }
    }

    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
  }
}
</style>
